﻿/**************************************************************************
创建时间:	2020/6/28 15:27:58    
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com

Copyright (c) zhcun.cn

描	述：
记	录：
***************************************************************************/
using System;
using System.Threading.Tasks;
using ZhCun.DBModel;
using ZhCun.Utils;
using ZhCun.Utils.Helpers;
using ZhCun.WebUtils.DB;

namespace ZhCun.WebUtils.Authorizes
{
    public class LoginStateMemory : LoginStateBase
    {
        /// <summary>
        /// 从数据库中异步获取所有未到期的token列表，并放入缓存(异步)
        /// </summary>
        public override void InitCache()
        {
            Task.Run(() =>
            {
                LoginStateBLL al = new LoginStateBLL();
                var userList = al.GetValidToken();
                foreach (var item in userList)
                {
                    LoginUser user = new LoginUser
                    {
                        Expires = DateTime.Now - item.ExpiresTime,
                        NotBefore = null,
                        RoleId = item.RoleId,
                        UserId = item.UserId,
                        UserName = item.UserName
                    };
                    Set(user);
                }

                LogHelper.LogObj.Info($"Token载入缓存: {userList.Count}");
                return userList.Count;
            });
        }

        public override string CreateToken(LoginUser user)
        {
            user.ExpiresTime = DateTime.Now.Add(user.Expires);

            return GuidHelper.NewId();
        }

        /// <summary>
        /// 获取LoginToken对象
        /// </summary>
        public override LoginUser Get(string token)
        {
            if (string.IsNullOrEmpty(token))
            {
                return null;
            }
            var r = MemoryCacheHelper.Get<LoginUser>(token);
            return r;
        }
        /// <summary>
        /// 设置缓存,并返回Token
        /// </summary>
        public override string Set(LoginUser user)
        {
            if (user == null) return null;
            var token = CreateToken(user);
            MemoryCacheHelper.Set(token, user, user.Expires);
            return token;
        }
        /// <summary>
        /// 移除缓存
        /// </summary>
        public override bool Remove(string token)
        {
            if (token.IsEmpty()) return false;
            MemoryCacheHelper.Remove(token);
            return true;
        }
        
        public override string RefreshToken(string token)
        {
            var user = Get(token);            
            //原 Token 2分钟后过期
            MemoryCacheHelper.Set(token, user,TimeSpan.FromMinutes(2));
            var newToken = CreateToken(user);
            MemoryCacheHelper.Set(newToken, user, user.Expires);
            return newToken;
        }
    }
}